package com.duan.nowcoder.community.controller;

import com.duan.nowcoder.community.annotation.LoginRequired;
import com.duan.nowcoder.community.entity.User;
import com.duan.nowcoder.community.service.FollowService;
import com.duan.nowcoder.community.service.LikeService;
import com.duan.nowcoder.community.service.UserService;
import com.duan.nowcoder.community.util.CommunityConstant;
import com.duan.nowcoder.community.util.CommunityUtil;
import com.duan.nowcoder.community.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {
    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value("${community.path.headerPath}")
    private String headerPath;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;


    @LoginRequired
    @GetMapping("/setting")
    public String getSettingPage() {
        return "/site/setting";
    }

    @LoginRequired
    @PostMapping("upload")
    public String uploadHeader(MultipartFile headerImage, Model model) {
        //判断图片是否为空
        if (headerImage == null) {
            model.addAttribute("error", "请先上传图片！");
            return "/site/setting";
        }
        //判断图片是否合法
        String fileName = headerImage.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if (!suffix.equals(".png") && !suffix.equals(".jpg") && !suffix.equals(".jpeg")) {
            model.addAttribute("error", "请上传png/jpg/jpeg格式的图片文件！");
            return "/site/setting";
        }
        //生成随机文件名
        fileName = CommunityUtil.generateUUID() + suffix;
        //确定文件存放路径
        File dest = new File(headerPath + "/" + fileName);
        //存储文件
        try {
            headerImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("文件存储失败" + e.getMessage());
            throw new RuntimeException("文件存储失败，服务器异常", e);
        }

        User user = hostHolder.getUser();
        String headerUrl = domain + contextPath + "/user/header/" + fileName;
        userService.updateUserHeader(user.getId(), headerUrl);
        return "redirect:/index";
    }

    //此时存到数据库了但还没上传到web
    @GetMapping("/header/{fileName}")
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        //找到服务器存放路径
        fileName = headerPath + "/" + fileName;
        //解析文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //响应的格式
        response.setContentType("image/" + suffix);

        try (FileInputStream stream = new FileInputStream(fileName);
             ServletOutputStream os = response.getOutputStream();) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = stream.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("读取头像失败", e);
        }
    }

    //修改用户密码
    @LoginRequired
    @PostMapping("/updatePassword")
    public String updatePassword(Model model, String newPassword, String oldPassword, String confirmPassword) {
        if (StringUtils.isBlank(confirmPassword)) {
            model.addAttribute("confirmPasswordMsg", "请再次输入！");
            return "/site/setting";
        }
        if (!newPassword.equals(confirmPassword)) {
            model.addAttribute("confirmPasswordMsg", "两次输入不相同！");
            return "/site/setting";
        }
        User user = hostHolder.getUser();
        Map<String, Object> map = userService.updatePassword(user.getId(), newPassword, oldPassword);
        if (!map.isEmpty()) {
            model.addAttribute("newPasswordMsg", map.get("newPasswordMsg"));
            System.out.println(map.get("newPasswordMsg"));
            model.addAttribute("oldPasswordMsg", map.get("oldPasswordMsg"));
            System.out.println(map.get("oldPasswordMsg"));
            return "/site/setting";
        }
        model.addAttribute("success", "修改密码成功，请重新登录！");
        return "redirect:/logout";
    }

    //查看用户信息
    @GetMapping("/profile/{id}")
    public String getProFile(@PathVariable("id") int userId, Model model) {
        //目标
        User user = userService.findUserById(userId);
        //我
        User me = hostHolder.getUser();
        model.addAttribute("user",user);
        //获得获赞的数量
        Long likeCount = likeService.findUserLike(userId);
        model.addAttribute("likeCount",likeCount);
        //是否已关注
        model.addAttribute("isFollow",followService.isFollower(me.getId(),ENTITY_TYPE_USER,userId));
        //获得粉丝的数量
        model.addAttribute("followerCount",followService.followerCount(userId,ENTITY_TYPE_USER));
        //获得博主的数量
        model.addAttribute("followeeCount",followService.followeeCount(userId,ENTITY_TYPE_USER));
        return "/site/profile";
    }
}
